package club.baimahu.pencil.miaosha.controller;


import club.baimahu.pencil.base.AjaxResult;
import club.baimahu.pencil.util.Base64;
import club.baimahu.pencil.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 * 
 * @author
 */
@RestController
public class CaptchaController
{
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String CAPTCHA_CODE_KEY = "CAPTCHA_CODE_KEY";

    int CAPTCHA_EXPIRATION = 2;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = UUID.randomUUID().toString();
        String verifyKey = CAPTCHA_CODE_KEY + uuid;

        redisTemplate.opsForValue().set(verifyKey,verifyCode,CAPTCHA_EXPIRATION,TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try
        {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(stream.toByteArray()));
            return ajax;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        finally
        {
            stream.close();
        }
    }
}
